/**
 * 3η ΓΕ 2013-2014 - Super Market
 * ΦΡΑΓΚΟΥΛΟΠΟΥΛΟΥ ΕΜΜΑΝΟΥΕΛΑ (69298)
 * ΧΑΛΔΑΣ ΧΑΡΑΛΑΜΠΟΣ (69305)
 * ΧΟΡΜΟΒΙΤΗΣ ΙΩΑΝΝΗΣ (69325)
 * ΧΟΥΣΤΟΥΛΑΚΗ ΕΥΑΓΓΕΛΙΑ (69327)
 */
package customerGUI;

import supermarket.StoreItem;
import java.awt.event.ItemEvent;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.INFORMATION_MESSAGE;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import model.*;
import supermarket.LocalBanks;

/**
 * Οθόνη Αγορών
 */
public class PurchaseForm extends javax.swing.JInternalFrame {

    private Customer myCustomer;
    /**
     * Constructor
     */
    public PurchaseForm() {
        initComponents();
        DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
        dtcr.setHorizontalAlignment(SwingConstants.CENTER);
        for (int i = 0; i < storeProducts.getColumnModel().getColumnCount(); ++i) {
            storeProducts.getColumnModel().getColumn(i).setCellRenderer(dtcr);
        }

        prepareProductStore();

        JTableHeader jtableHeader = storeProducts.getTableHeader();
        DefaultTableCellRenderer rend = (DefaultTableCellRenderer) storeProducts.getTableHeader().getDefaultRenderer();
        rend.setHorizontalAlignment(SwingConstants.CENTER);
        jtableHeader.setDefaultRenderer(rend);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        SuperMarketPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SuperMarketPU").createEntityManager();
        productQuery = java.beans.Beans.isDesignTime() ? null : SuperMarketPUEntityManager.createQuery("SELECT p FROM Product p");
        productList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(productQuery.getResultList());
        PurchasesPanel = new javax.swing.JPanel();
        storeCombo = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        storeProducts = new javax.swing.JTable();
        addToBasketButton = new javax.swing.JButton();
        gotToBasketButton = new javax.swing.JButton();
        storeLabel = new javax.swing.JLabel();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);

        storeCombo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                storeCombostoreListStateChanged(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, productList, storeProducts);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${code}"));
        columnBinding.setColumnName("Κωδικός");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${price}"));
        columnBinding.setColumnName("Τιμή");
        columnBinding.setColumnClass(Float.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${points}"));
        columnBinding.setColumnName("Πόντοι");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane2.setViewportView(storeProducts);

        addToBasketButton.setText("Προσθήκη στο καλάθι");
        addToBasketButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addToBasketButtonActionPerformed(evt);
            }
        });

        gotToBasketButton.setText("Μετάβαση στο καλάθι");
        gotToBasketButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                gotToBasketButtonActionPerformed(evt);
            }
        });

        storeLabel.setText("Κατάστημα");

        org.jdesktop.layout.GroupLayout PurchasesPanelLayout = new org.jdesktop.layout.GroupLayout(PurchasesPanel);
        PurchasesPanel.setLayout(PurchasesPanelLayout);
        PurchasesPanelLayout.setHorizontalGroup(
            PurchasesPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(PurchasesPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(PurchasesPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(PurchasesPanelLayout.createSequentialGroup()
                        .add(storeCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 306, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .add(PurchasesPanelLayout.createSequentialGroup()
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 531, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(PurchasesPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(gotToBasketButton)
                            .add(addToBasketButton))
                        .add(18, 18, 18))
                    .add(PurchasesPanelLayout.createSequentialGroup()
                        .add(storeLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 83, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(0, 0, Short.MAX_VALUE))))
        );
        PurchasesPanelLayout.setVerticalGroup(
            PurchasesPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(PurchasesPanelLayout.createSequentialGroup()
                .add(18, 18, 18)
                .add(storeLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(storeCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(PurchasesPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 273, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(PurchasesPanelLayout.createSequentialGroup()
                        .add(addToBasketButton)
                        .add(18, 18, 18)
                        .add(gotToBasketButton)))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(PurchasesPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(PurchasesPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

     private void storeCombostoreListStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_storeCombostoreListStateChanged
         // TODO add your handling code here:
         if (evt.getStateChange() == ItemEvent.SELECTED) {
             fillProductStoreLists((StoreItem) storeCombo.getSelectedItem());
             Basket b = Basket.getInstance();
             b.initStore(((StoreItem) storeCombo.getSelectedItem()).getStore());
             this.setTitle(b.getStatus());
         }
     }//GEN-LAST:event_storeCombostoreListStateChanged

    public void fillProductStoreLists(StoreItem storeItem) {
		//DefaultListModel lsm1 = (DefaultListModel) storeProducts.getModel();
        //lsm1.removeAllElements();
        productList.clear();
        TypedQuery<Product> q = SuperMarketPUEntityManager
                .createNamedQuery("Product.findAll",
                        Product.class);
        List<Product> ls = q.getResultList();
        for (int i = 0; i < ls.size(); ++i) {
            List<Store> belongsTo = (List<Store>) ls.get(i).getStoreList();
            boolean found = false;
            for (int j = 0; j < belongsTo.size(); ++j) {
                if (belongsTo.get(j).getStoreId() == storeItem.getStore().getStoreId()) {
                    found = true;
                    break;
                }
            }
            if (found) {
                productList.add(ls.get(i));
                //	lsm1.addElement(new ProductItem(ls.get(i)));
            }

        }
    }

    public void prepareProductStore() {
        storeCombo.removeAllItems();
        TypedQuery<Store> q1 = SuperMarketPUEntityManager
                .createNamedQuery("Store.findAll",
                        Store.class);
        if (q1.getResultList().size() == 0) {
            return;
        }
        List<Store> ls = q1.getResultList();
        for (int i = 0; i < ls.size(); ++i) {
            storeCombo.addItem(new StoreItem(ls.get(i)));
        }
        fillProductStoreLists((StoreItem) storeCombo.getSelectedItem());
    }

     private void gotToBasketButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_gotToBasketButtonActionPerformed
         // TODO add your handling code here:
         BasketDialog bd = new BasketDialog(null, true);
         bd.setLocationRelativeTo(null);
         bd.setCustomer(myCustomer);
         bd.setVisible(true);
         Basket b = Basket.getInstance();
         this.setTitle(b.getStatus());
     }//GEN-LAST:event_gotToBasketButtonActionPerformed

     private void addToBasketButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addToBasketButtonActionPerformed
         // TODO add your handling code here:
         int row = storeProducts.getSelectedRow();
         if (row < 0) {
            JOptionPane.showMessageDialog(this, "Δεν έχετε επιλέξει εγγραφή.",
                     "Προσοχή!", INFORMATION_MESSAGE);
             return;
         }
         Product product = productList.get(row);
         SelectAmountDialog ad = new SelectAmountDialog(null, true, product.getName());
         ad.setLocationRelativeTo(null);
         ad.setVisible(true);
         if (ad.getValue() != 0) {
             Basket b = Basket.getInstance();
             ProductPurchase pr = new ProductPurchase();
             pr.setProductId(product);
             pr.setQuantity(ad.getValue());
             b.add(pr);
             this.setTitle(b.getStatus());
             JOptionPane.showMessageDialog(this, "Προσθέσατε " + ad.getValue() +
                     " τεμάχια από το προϊόν: " + product.getName()
                     , "Προσθήκη στο καλάθι", INFORMATION_MESSAGE);
         }
     }//GEN-LAST:event_addToBasketButtonActionPerformed

    public void setCustomer(Customer c) {
        myCustomer = c;

        LocalBanks lb = new LocalBanks();
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PurchasesPanel;
    private javax.persistence.EntityManager SuperMarketPUEntityManager;
    private javax.swing.JButton addToBasketButton;
    private javax.swing.JButton gotToBasketButton;
    private javax.swing.JScrollPane jScrollPane2;
    private java.util.List<model.Product> productList;
    private javax.persistence.Query productQuery;
    private javax.swing.JComboBox storeCombo;
    private javax.swing.JLabel storeLabel;
    private javax.swing.JTable storeProducts;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}
